﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;

namespace RegexEditor
{
	public class MatchHighlightTextBox : HighlightTextBox
	{
		#region Public Members

		public List<Color> HighlightColors { get; protected set; }

		public void Highlight(IEnumerable<Match> matches)
		{
			Highlight(matches.Select(m => StringSegment.FromCapture(m)));
		}

		public void Highlight(IEnumerable<Group> groups)
		{
			Highlight(groups.Select(m => StringSegment.FromCapture(m)));
		}

		public void Highlight(IEnumerable<Capture> captures)
		{
			Highlight(captures.Select(m => StringSegment.FromCapture(m)));
		}

		public void Highlight(IEnumerable<StringSegment> segments)
		{
			try
			{
				IsUpdating = true;

				Color highlightColor = HighlightColors[0];
				int highlightIndex = 0;

				RemoveFormatting();

				foreach (StringSegment segment in segments)
				{
					Highlight(segment.Index, segment.Length, Color.Transparent, highlightColor);
					highlightIndex++;

					if (highlightIndex > HighlightColors.Count - 1)
						highlightIndex = 0;

					highlightColor = HighlightColors[highlightIndex];
				}
			}
			finally
			{
				IsUpdating = false;
			}
		}

		public void Select(Capture capture)
		{
			if (capture != null)
			{
				SelectionStart = capture.Index;
				SelectionLength = capture.Length;
			}
		}

		#endregion

		#region Protected Members

		protected bool IsUpdating { get; private set; }

		protected override void InitializeComponent()
		{
			base.InitializeComponent();
			HideSelection = false;
			HighlightColors = new List<Color> { Color.Yellow, Color.Cyan };
		}

		protected override void OnTextChanged(EventArgs e)
		{
			if (!IsUpdating)
				base.OnTextChanged(e);
		}

		protected override void OnSelectionChanged(EventArgs e)
		{
			if (!IsUpdating)
				base.OnSelectionChanged(e);
		}

		#endregion
	}
}
